<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '购物车',
  },
}
</route>
<template>
  <view class="page">
    <view class="sticky top-0 z-10 bg-white w-full">
      <k-navbar :isMain="true"></k-navbar>
      <view class="mt-[20px] text-right mr-5 text-[#343434] text-sm" @click="toggleEditStatus">
        {{ state.isEdit ? '完成' : '编辑' }}
      </view>
    </view>

    <view class="px-4">
      <k-list :is-empty="!(carList && carList.length)" :loading="loading">
        <!-- @change="handleSelectChange" -->
        <wd-checkbox-group :modelValue="state.selectedBuy" size="36rpx">
          <view class="flex items-center mt-4" v-for="item in carList" :key="item.id">
            <wd-checkbox :modelValue="item.id" @change="handleSelectChange(item)"></wd-checkbox>
            <!-- @click="handleClickProduct(item)" -->
            <view class="flex-1">
              <around :data="item.goods" :showSales="false"
                @click="to(`pages-sub/product/product-detail?id=${item.goods_id}`)">
                <template #price>
                  <view class="flex justify-between items-center w-full">
                    <text>{{ item.goods_item.sell_price }}</text>
                    <!-- <text class="text-sm">x{{ item.goods_num }}</text> -->
                  </view>
                </template>
                <view class="mt-auto">
                  <discount-bar :level-name="item.levelName" :price="item.goods_item.member_price"></discount-bar>
                </view>
              </around>
            </view>
          </view>
        </wd-checkbox-group>
      </k-list>
    </view>

    <float-bottom :safeAreaInsetBottom="false" :fit-tab-bar="true">
      <view class="h-full flex items-center pl-[20rpx] pr-[30rpx]">
        <view class="pr-4 flex-1 flex justify-between items-center">
          <wd-checkbox v-model="isAllSelected" size="36rpx">
            <text class="text-sm text-[#161616]">全选</text>
          </wd-checkbox>
          <view v-if="!state.isEdit && carInfo">
            <text class="text-[#9A9A9A] text-[26rpx] mr-[3rpx]">合计</text>
            <text class="text-[34rpx] text-base font-bold">
              <text class="text-sm font-normal">￥</text>
              {{ carInfo.total_amount }}
            </text>
          </view>
        </view>
        <wd-button :round="false" :block="true" :plain="state.isEdit" custom-class="w-[260rpx]" @click="handleAction">
          <text class="text-[26rpx]">
            <template v-if="state.isEdit">删除</template>
            <template v-else>结算({{ state.selectedBuy.length }})</template>
          </text>
        </wd-button>
      </view>
    </float-bottom>
  </view>
</template>

<script setup>
import useReachBottomLoadMore from '@/hooks/useReachBottomLoadMore'
import { fetchCarList, selectedCar, removeCar } from '@/service/car'
import { showToast } from '@/utils/uni'
import { to } from '@/utils/navigation'
const {
  data: carList,
  refresh,
  loading,
  resource: carInfo,
  run,
} = useReachBottomLoadMore(fetchCarList)

const state = ref({
  isEdit: false,
  selectedBuy: [],
})

onShow(() => {
  refresh()
})

const isAllSelected = computed({
  get() {
    return carList.value.length && state.value.selectedBuy.length >= carList.value.length
  },
  set(v) {
    if (!carList.value.length) return
    state.value.selectedBuy = carList.value.map((item) => item.id);
    selectedBefore({
      cart_id: state.value.selectedBuy,
      selected: Number(v),
    }).then((res) => {
      carList.value = carList.value.map((item) => {
        item.selected = v
        return item
      })
    })
  },
})

watch(
  () => carList.value,
  () => {
    state.value.selectedBuy = carList.value.filter((item) => item.selected).map((item) => item.id)
  },
  { deep: true },
)

function getSettlementInfo() {
  fetchCarList().then((res) => {
    const { total_amount } = res.data
    carInfo.value.total_amount = total_amount
  })
}

function handleAction() {
  if (!state.value.selectedBuy.length) return showToast('请选择商品')
  if (state.value.isEdit) {
    removeCar(state.value.selectedBuy).then((res) => {
      carList.value = carList.value.filter((item) => !state.value.selectedBuy.includes(item.id))
    })
  } else {
    to(`pages-sub/product/create-order?cart_id=${state.value.selectedBuy.join()}&source=cart`)
  }
}

async function selectedBefore(params) {
  const res = await selectedCar(params)
  await getSettlementInfo()
  return res
}

function toggleEditStatus() {
  state.value.isEdit = !state.value.isEdit
}

function handleSelectChange(item) {
  const nextStatus = Number(!item.selected)
  selectedBefore({
    cart_id: item.id,
    selected: nextStatus,
  }).then(() => {
    const index = carList.value.findIndex((el) => el.id === item.id)
    carList.value[index].selected = nextStatus
  })
}
</script>

<style lang="scss" scoped>
.page {
  padding-bottom: 116rpx;
}
</style>
